package com.mypack.bookStore.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mypack.bookStore.entity.RoleEntity;
import com.mypack.bookStore.entity.UserEntity;
import com.mypack.bookStore.services.UCenterService;
@Service
public class WebUserDetailsService implements UserDetailsService {
	private static Logger logger=LoggerFactory.getLogger(WebUserDetailsService.class);
	protected MessageSourceAccessor messagesAccessor=SpringSecurityMessageSource.getAccessor();
	@Autowired
	private UCenterService uCenterService;
	@Transactional
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		//该方法负责实现验证授权
		UserEntity userEntity = uCenterService.getUserByUserName(username);
		if(null == userEntity){
			throw new UsernameNotFoundException(messagesAccessor.getMessage("User.notFound",new Object[]{username},"Username {0} not found"));
		}
		int userId= userEntity.getId();
		String password=userEntity.getPassWord();
		boolean userEnabled=userEntity.getStatus()==1;
		//读取当前用户有哪些角色权限
		Set<RoleEntity> userRoles = userEntity.getRoles();
		//装载当前用户授权容器
		Collection<GrantedAuthority> authorities= new ArrayList<GrantedAuthority>();
		for(RoleEntity userRole:userRoles){
			SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_"+userRole.getId());
			authorities.add(simpleGrantedAuthority);
		}
		if(username.equals("admin")){
			authorities.add(new SimpleGrantedAuthority("ROLE_SUPER"));
		}
		WebUserDetails webUserDetails = new WebUserDetails(userId,username,password,userEnabled,authorities);
		return webUserDetails;
	}

}
